package com.heima.search.listen;

import com.heima.common.wemedia.NewsUpOrDownConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Component
@Slf4j
public class ArticleAddOrRemoveListener {

    @Autowired
    ArticleSearchService articleSearchService;
    @Autowired
    ArticleFeign articleFeign;


    /**
     * 监听文章上架消息
     *
     * @param articleId
     */
    @RabbitListener(queues = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE)
    public void listenNewsUpMsg(String articleId) {
        log.info("接收到文章上架消息,  消息内容:{}", articleId);
        //根据articleId查询文章信息,将文章信息 添加到es索引库
        //远程查询article信息
        ResponseResult<SearchArticleVO> result = articleFeign.findArticle(Long.valueOf(articleId));
        if (!result.checkCode()) {
            log.error("索引库添加失败 远程调用文章信息失败   文章id: {}", articleId);
        }
        SearchArticleVO searchArticleVO = result.getData();
        if (searchArticleVO == null) {
            log.error("索引库添加失败 未获取到对应文章信息   文章id: {}", articleId);
        }
        try {
            articleSearchService.saveArticle(searchArticleVO);
            log.info("成功更新索引信息   add: {}", articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}", articleId, e.getMessage());
        }
    }

    /**
     * 监听文章下架消息
     *
     * @param articleId
     */
    @RabbitListener(queues = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE)
    public void listenNewsDownMsg(String articleId) {
        log.info("接收到文章下架消息,  消息内容:{}", articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            log.info("成功更新索引信息   delete: {}", articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}", articleId, e.getMessage());
        }
    }
}
